package com.example.amap.ui.map.ui.page

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowLeft
import androidx.compose.material.icons.filled.Clear
import androidx.compose.material.icons.filled.Place
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.VerticalDivider
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.State
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.amap.search.bean.SearchSuggestInfo
import com.example.amap.ui.map.ui.style.buttonModifier
import com.example.amap.ui.map.ui.viewmodel.search.SearchViewModel

@Preview
@Composable
fun PageSearch(onBackClick: () -> Unit = {}) {
    Column(
        modifier = Modifier
            .buttonModifier()
            .width(350.dp)
    ) {
        val viewModel = viewModel<SearchViewModel>()
        SearchBar(
            viewModel.hasFocus,
            viewModel::onFocusChange,
            viewModel.searchText,
            viewModel::onSearchTextChange,
            onBackClick = onBackClick
        )
        SuggestionList(viewModel.suggestList.value, viewModel.searchText.value)
    }
}

@Composable
private fun SearchBar(
    hasFocus: State<Boolean>,
    onFocusChanged: (Boolean) -> Unit,
    searchText: State<String>,
    onSearchTextChanged: (String) -> Unit,
    onBackClick: () -> Unit = {}
) {
    val focusRequester = remember { FocusRequester() }
    LaunchedEffect(Unit) {
        focusRequester.requestFocus()
    }
    BasicTextField(
        value = searchText.value,
        onValueChange = onSearchTextChanged,
        singleLine = true,
        textStyle = TextStyle(fontSize = MaterialTheme.typography.bodyLarge.fontSize),
        modifier = Modifier
            .size(350.dp, 50.dp)
            .padding(horizontal = 8.dp)
            .focusRequester(focusRequester)
            .onFocusChanged { onFocusChanged(it.isFocused) },
        cursorBrush = SolidColor(MaterialTheme.colorScheme.primary),
        decorationBox = { innerTextField ->
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Icon(
                    imageVector = Icons.AutoMirrored.Filled.KeyboardArrowLeft,
                    contentDescription = null,
                    modifier = Modifier
                        .size(32.dp)
                        .clickable { onBackClick() }
                )

                Spacer(modifier = Modifier.width(8.dp))

                Box(
                    modifier = Modifier
                        .weight(1f)
                ) {
                    if (searchText.value.isEmpty())
                        Text(
                            text = "请输入搜索内容",
                            color = Color.Gray,
                            fontSize = MaterialTheme.typography.bodyLarge.fontSize
                        )

                    innerTextField()
                }

                // 存在焦点，且有输入内容时，显示叉号
                if (hasFocus.value && searchText.value.isNotEmpty()) {
                    Icon(imageVector = Icons.Filled.Clear,
                        contentDescription = null,
                        modifier = Modifier
                            .size(24.dp)
                            .clickable { onSearchTextChanged("") })
                }

                VerticalDivider(modifier = Modifier.padding(vertical = 16.dp, horizontal = 4.dp))

                Text(
                    text = "搜索",
                    fontSize = MaterialTheme.typography.bodyLarge.fontSize,
                    color = Color.Blue
                )
            }
        }
    )
}

@Composable
private fun SuggestionList(itemList: List<SearchSuggestInfo>, searchText: String) {
    LazyColumn {
        itemsIndexed(itemList) { index, item ->
            Column {
                if (index != 0) {
                    HorizontalDivider(
                        modifier = Modifier.padding(
                            horizontal = 12.dp,
                            vertical = 8.dp
                        )
                    )
                }
                SuggestionItem(item, searchText)
            }
        }
    }
}

@Composable
private fun SuggestionItem(item: SearchSuggestInfo, searchText: String) {
    Row(verticalAlignment = Alignment.CenterVertically) {
        Icon(
            imageVector = if (item.address.isNotBlank()) Icons.Filled.Place else Icons.Filled.Search,
            contentDescription = null,
            modifier = Modifier
                .padding(horizontal = 12.dp)
                .size(18.dp)
        )
        Column {
            val name = item.name
            val startIndex = item.name.indexOf(searchText, ignoreCase = true)
            val endIndex = startIndex + searchText.length
            Text(
                buildAnnotatedString {
                    if (startIndex == -1) {
                        append(name)
                    } else {
                        append(name.substring(0, startIndex))
                        withStyle(style = SpanStyle(color = Color.Blue)) {
                            append(name.substring(startIndex, endIndex))
                        }
                        append(name.substring(endIndex))
                    }
                }
            )
            if (item.address.isNotBlank()) {
                Text(text = item.address, color = Color.Gray)
            }
        }
    }
}